package com.example.javaweb;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/loginservlet")
public class loginservlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //获取用户输入信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //判断输入信息是否正确
        if("张三".equals(username)&&"123456".equals(password)){
            //输入正确，跳转到首页，显示登录用户信息
            //将用户保存
            HttpSession session = req.getSession();
            session.setAttribute("user",new User(username,password);
            //设置存活时间
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60);
            //添加到响应头字段
            resp.addCookie(cookie);
            resp.sendRedirect("loginsuccess.jsp");

        }else {
            //不正确，重新输入
            writer.write("登录失败，请重新登录");
            resp.setHeader("Refresh","3;url='login.jsp'");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }


}